package com.ruoyi.adapayDiv.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.huifu.adapay.model.AdapayCommon;
import com.huifu.adapay.model.PaymentConfirm;
import com.ruoyi.adapayBalance.service.IAdapayBalanceService;
import com.ruoyi.adapayBalancepay.domain.AdapayBalancepay;
import com.ruoyi.adapayBalancepay.service.IAdapayBalancepayService;
import com.ruoyi.adapayMember.domain.AdapayMember;
import com.ruoyi.adapayMember.service.IAdapayMemberService;
import com.ruoyi.adapayRecord.domain.AdapayRecord;
import com.ruoyi.adapayRecord.service.IAdapayRecordService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.coupons.domain.CouponsMember;
import com.ruoyi.coupons.service.ICouponsMemberService;
import com.ruoyi.coupons.service.ICouponsService;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.order.service.IStoreProductOrderService;
import com.ruoyi.shopping.domain.MallOrderMesh;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.adapayDiv.mapper.AdapayDivMapper;
import com.ruoyi.adapayDiv.domain.AdapayDiv;
import com.ruoyi.adapayDiv.service.IAdapayDivService;

/**
 * 分账记录支付确认记录Service业务层处理
 *
 * @author ch
 * @date 2022-02-28
 */
@Service
public class AdapayDivServiceImpl implements IAdapayDivService
{
    @Autowired
    private AdapayDivMapper adapayDivMapper;
    @Autowired
    private IStoreProductOrderService storeProductOrderService;
    @Autowired
    private IAdapayRecordService adapayRecordService;
    @Autowired
    private IAdapayMemberService adaPayMemberService;
    @Autowired
    private IAdapayDivService adapayDivService;
    @Autowired
    private IAdapayBalanceService adapayBalanceService;
    @Autowired
    private ICouponsService couponsService;
    @Autowired
    private ICouponsMemberService couponsMemberService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAdapayBalancepayService adapayBalancepayService;
    /**
     * 查询分账记录支付确认记录
     *
     * @param id 分账记录支付确认记录主键
     * @return 分账记录支付确认记录
     */
    @Override
    public AdapayDiv selectAdapayDivById(Long id)
    {
        return adapayDivMapper.selectAdapayDivById(id);
    }

    /**
     * 查询分账记录支付确认记录列表
     *
     * @param adapayDiv 分账记录支付确认记录
     * @return 分账记录支付确认记录
     */
    @Override
    public List<AdapayDiv> selectAdapayDivList(AdapayDiv adapayDiv)
    {
        return adapayDivMapper.selectAdapayDivList(adapayDiv);
    }

    /**
     * 新增分账记录支付确认记录
     *
     * @param adapayDiv 分账记录支付确认记录
     * @return 结果
     */
    @Override
    public int insertAdapayDiv(AdapayDiv adapayDiv)
    {
        adapayDiv.setCreateTime(DateUtils.getNowDate());
        return adapayDivMapper.insertAdapayDiv(adapayDiv);
    }

    /**
     * 修改分账记录支付确认记录
     *
     * @param adapayDiv 分账记录支付确认记录
     * @return 结果
     */
    @Override
    public int updateAdapayDiv(AdapayDiv adapayDiv)
    {
        adapayDiv.setUpdateTime(DateUtils.getNowDate());
        return adapayDivMapper.updateAdapayDiv(adapayDiv);
    }

    /**
     * 批量删除分账记录支付确认记录
     *
     * @param ids 需要删除的分账记录支付确认记录主键
     * @return 结果
     */
    @Override
    public int deleteAdapayDivByIds(Long[] ids)
    {
        return adapayDivMapper.deleteAdapayDivByIds(ids);
    }


    /**
     * 批量逻辑删除分账记录支付确认记录
     *
     * @param ids 需要删除的分账记录支付确认记录主键
     * @return 结果
     */
    @Override
    public int logicDeleteAdapayDiv(Long[] ids,String delType,Long delUser)
    {
        return adapayDivMapper.logicDeleteAdapayDiv(ids,delType,delUser);
    }

    /**
     * 删除分账记录支付确认记录信息
     *
     * @param id 分账记录支付确认记录主键
     * @return 结果
     */
    @Override
    public int deleteAdapayDivById(Long id)
    {
        return adapayDivMapper.deleteAdapayDivById(id);
    }

    /**
     * 订单分账
     * @param orderid
     */
    @Override
    public void orderDiv(Long orderid){
        StoreProductOrder storeProductOrder= storeProductOrderService.selectStoreProductOrderById(orderid);
        if(DicConstants.BILLING_STATE_End.getCode().equals(storeProductOrder.getBillingState())){
            //
            return;
        }
        Long  storeId= storeProductOrder.getStoreId();
        AdapayMember adapayMemberQuery=new AdapayMember();
        adapayMemberQuery.setStoreId(storeId);
        List<AdapayMember> listMember= adaPayMemberService.selectAdapayMemberList(adapayMemberQuery);
        AdapayMember adapayMember=new AdapayMember();
          if(listMember.size()>0){
              adapayMember=listMember.get(0);
          }else{
              return;
          }
        String payOrderNo=storeProductOrder.getPayOrderNo();
        AdapayRecord adapayRecordQuery=new AdapayRecord();
        adapayRecordQuery.setPayOrderId(payOrderNo);
        List<AdapayRecord>  list=adapayRecordService.selectAdapayRecordList(adapayRecordQuery);
        AdapayRecord adapayRecord=null;
        if(list.size()>0){
            adapayRecord=list.get(0);
        }else{
            return;
        }
        BigDecimal storeMoney=storeProductOrder.getStoreMoney();//商家金额
        BigDecimal platformMoney=storeProductOrder.getPlatformMoney();//平台金额
        BigDecimal payPrice=storeProductOrder.getPayPrice();//平台金额
        String paymentId=adapayRecord.getPaymentId();
        Map<String, Object> confirmParams = new HashMap<>();
        confirmParams.put("payment_id", paymentId);
        String order_no="div" + System.currentTimeMillis();
        confirmParams.put("order_no",order_no );
        confirmParams.put("confirm_amt", payPrice.toString());
        //confirmParams.put("description", "description");
        List<Map<String, String>> memberList = new ArrayList<>();
        //平台分佣
        if( platformMoney.compareTo(new BigDecimal("0"))>0){
            Map<String, String> divMember = new HashMap<>();
            divMember.put("member_id", "0");//分账用户 Member对象 的 id；若是商户本身时，传入0
            divMember.put("amount", platformMoney.toString());//分账金额，精确到分
            memberList.add(divMember);
        }

        //商家收取
        Map<String, String> divMember1 = new HashMap<>();
        divMember1.put("member_id",adapayMember.getAdapayMemberId() );//分账用户 Member对象 的 id；若是商户本身时，传入0
        divMember1.put("amount", storeMoney.toString());//分账金额，精确到分
        memberList.add(divMember1);
        confirmParams.put("div_members", memberList);
        confirmParams.put("fee_mode", "O");
        AdapayDiv adapayDiv=new AdapayDiv();
        adapayDiv.setProductOrderId(orderid);
        adapayDiv.setPaymentId(paymentId);
        adapayDiv.setTotalMoney(payPrice);
        adapayDiv.setDivMoney("");
        adapayDiv.setDivType(DicConstants.DIV_TYPE_ORDER.getCode());
        adapayDiv.setReqParam(confirmParams.toString());
        adapayDiv.setReqState(DicConstants.SYS_Y.getCode());
        Map<String, Object> paymentConfirm=null;
        StoreProductOrder storeProductOrderUpdate=new StoreProductOrder();
        storeProductOrderUpdate.setId(storeProductOrder.getId());
        try{
            paymentConfirm= PaymentConfirm.create(confirmParams);
        }catch (Exception e){
            adapayDiv.setReqFailMsg(e.getMessage());
            adapayDiv.setReqState(DicConstants.SYS_N.getCode());
            adapayDivService.insertAdapayDiv(adapayDiv);
            return;
        }
        adapayDiv.setResParam(paymentConfirm.toString());
        String error_code = (String) paymentConfirm.get("error_code");
        if (null != error_code) {
            String error_msg = (String) paymentConfirm.get("error_msg");
            System.out.println("error_code:" + error_code + "............." + error_msg);
            adapayDiv.setReqFailMsg(error_msg);
            adapayDiv.setReqState(DicConstants.SYS_N.getCode());
            storeProductOrderUpdate.setBillingState(DicConstants.BILLING_STATE_Fail.getCode());
        }else{
            adapayDiv.setPaymentConfirmId((String)paymentConfirm.get("id"));


            storeProductOrderUpdate.setBillingState(DicConstants.BILLING_STATE_End.getCode());
            storeProductOrderUpdate.setBillingTime(new Date());

            adapayBalanceService.handleBalance(storeId,storeMoney,DicConstants.HANDLE_BALANCE_ADD.getCode(),storeProductOrder.getProductName(),"订单id:"+storeProductOrder.getOrderId(),DicConstants.BUSTYPE_BALANCE_DIV.getCode());
            adapayBalanceService.handleBalance(null,platformMoney,DicConstants.HANDLE_BALANCE_ADD.getCode(),storeProductOrder.getProductName(),"订单id:"+storeProductOrder.getOrderId(),DicConstants.BUSTYPE_BALANCE_DIV.getCode());
            platformCouponDiv(storeProductOrder,adapayMember);
        }
        storeProductOrderService.updateStoreProductOrder(storeProductOrderUpdate);
        adapayDivService.insertAdapayDiv(adapayDiv);

    }

    @Override
    public void mallOrderDiv(Long storeId, AdapayMember adapayMember, MallOrderMesh mesh,BigDecimal needTransMoney) {
        {
            //测试使用只支付0.01
            //平台红包相当于给门店的补助需要从余额分账给门店
            String app_id=configService.selectConfigByKey("adpay_app_id");

            AdapayBalancepay adapayBalancepay=new AdapayBalancepay();
            adapayBalancepay.setProductOrderId(mesh.getId());
//            adapayBalancepay.setCouponsMemberId(CouponsMemberId);
            adapayBalancepay.setReqState(DicConstants.SYS_Y.getCode());
            String order_no="balancePay" + System.currentTimeMillis();
            Map<String, Object> balanceParam = new  HashMap<String, Object>(4);
            balanceParam.put("app_id", app_id);
            balanceParam.put("adapay_func_code", "settle_accounts.balancePay");
            balanceParam.put("order_no", order_no);
            balanceParam.put("out_member_id", "0");
            balanceParam.put("in_member_id", adapayMember.getAdapayMemberId());
            balanceParam.put("trans_amt", needTransMoney);
            balanceParam.put("goods_title", "分销商品入账");
            balanceParam.put("goods_desc", "用户分销商品，订单编号："+mesh.getId());
            Map<String, Object> paymentResult=null;
            try{
                paymentResult = AdapayCommon.requestAdapay(balanceParam);

            }catch (Exception e){
                adapayBalancepay.setReqState(DicConstants.SYS_N.getCode());
                adapayBalancepay.setReqFailMsg(e.getMessage());
                adapayBalancepayService.insertAdapayBalancepay(adapayBalancepay);
                return;
            }
            adapayBalancepay.setResParam(paymentResult.toString());
            String error_code = (String) paymentResult.get("error_code");
            if (null != error_code) {

                String error_msg = (String) paymentResult.get("error_msg");
                System.out.println("error_code:" + error_code + "............." + error_msg);
                adapayBalancepay.setReqState(DicConstants.SYS_N.getCode());
                adapayBalancepay.setReqFailMsg(error_msg);
                adapayBalancepayService.insertAdapayBalancepay(adapayBalancepay);
                return ;
            }
            adapayBalancepayService.insertAdapayBalancepay(adapayBalancepay);
            //门店增加
            adapayBalanceService.handleBalance(storeId,needTransMoney,DicConstants.HANDLE_BALANCE_ADD.getCode(),"商品分佣","订单id:"+mesh.getOrderId(),DicConstants.BUSTYPE_BALANCE_MALL_DIV.getCode());
            //平台减少
//            adapayBalanceService.handleBalance(null,needTransMoney,DicConstants.HANDLE_BALANCE_SUB.getCode(),mesh.getName(),"订单id:"+mesh.getOrderId(),DicConstants.BUSTYPE_BALANCE_BalancePay.getCode());


        }
    }

    /**
     * 红包分账，平台红包才需要
     */
    private void platformCouponDiv(StoreProductOrder storeProductOrder, AdapayMember adapayMember){
        Long CouponsMemberId=  storeProductOrder.getCouponId();
        if(null!=CouponsMemberId){
            CouponsMember couponsMember= couponsMemberService.selectCouponsMemberById(CouponsMemberId);
            if(null!=couponsMember){
               if(DicConstants.BELONG_TYPE_Plateform.getCode().equals( couponsMember.getBelongType())){
                   Long  storeId= storeProductOrder.getStoreId();
                   BigDecimal deductionPrice=storeProductOrder.getDeductionPrice();
                   //测试使用只支付0.01
                   //平台红包相当于给门店的补助需要从余额分账给门店
                   String app_id=configService.selectConfigByKey("adpay_app_id");

                   AdapayBalancepay adapayBalancepay=new AdapayBalancepay();
                   adapayBalancepay.setProductOrderId(storeProductOrder.getId());
                   adapayBalancepay.setCouponsMemberId(CouponsMemberId);
                   adapayBalancepay.setReqState(DicConstants.SYS_Y.getCode());
                   String order_no="balancePay" + System.currentTimeMillis();
                   Map<String, Object> balanceParam = new  HashMap<String, Object>(4);
                   balanceParam.put("app_id", app_id);
                   balanceParam.put("adapay_func_code", "settle_accounts.balancePay");
                   balanceParam.put("order_no", order_no);
                   balanceParam.put("out_member_id", "0");
                   balanceParam.put("in_member_id", adapayMember.getAdapayMemberId());
                   balanceParam.put("trans_amt", deductionPrice);
                   balanceParam.put("goods_title", "平台优惠券补贴");
                   balanceParam.put("goods_desc", "用户使用平台优惠券，订单编号："+storeProductOrder.getId());
                   Map<String, Object> paymentResult=null;
                   try{
                       paymentResult = AdapayCommon.requestAdapay(balanceParam);

                   }catch (Exception e){
                       adapayBalancepay.setReqState(DicConstants.SYS_N.getCode());
                       adapayBalancepay.setReqFailMsg(e.getMessage());
                       adapayBalancepayService.insertAdapayBalancepay(adapayBalancepay);
                       return;
                   }
                   adapayBalancepay.setResParam(paymentResult.toString());
                   String error_code = (String) paymentResult.get("error_code");
                   if (null != error_code) {

                       String error_msg = (String) paymentResult.get("error_msg");
                       System.out.println("error_code:" + error_code + "............." + error_msg);
                       adapayBalancepay.setReqState(DicConstants.SYS_N.getCode());
                       adapayBalancepay.setReqFailMsg(error_msg);
                       adapayBalancepayService.insertAdapayBalancepay(adapayBalancepay);
                       return ;
                   }
                   adapayBalancepayService.insertAdapayBalancepay(adapayBalancepay);
                   //门店增加
                   adapayBalanceService.handleBalance(storeId,deductionPrice,DicConstants.HANDLE_BALANCE_ADD.getCode(),storeProductOrder.getProductName(),"订单id:"+storeProductOrder.getOrderId(),DicConstants.BUSTYPE_BALANCE_BalancePay.getCode());
                  //平台减少
                   adapayBalanceService.handleBalance(null,deductionPrice,DicConstants.HANDLE_BALANCE_SUB.getCode(),storeProductOrder.getProductName(),"订单id:"+storeProductOrder.getOrderId(),DicConstants.BUSTYPE_BALANCE_BalancePay.getCode());

               }
            }
        }

    }
}
